package com.marver.common.utils;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * Created by Myco on 2017/6/8.
 * Description: 自动给bean赋值，Integer自动赋0，String自动赋""
 * 注，仅用于单表生成的etntity
 */
public class BeanUtil {
    /**
     * 自动赋值
     * @param clazz
     */
    public static <T> T autoAssign(Class<T> clazz) throws Exception {
        T obj = clazz.newInstance();//获取实体
        try {
            Field[] fields = clazz.getDeclaredFields();//获取字段
            for (Field field : fields) {
                String fieldName = field.getName();

                Object value = null;
                System.out.println(field.getType());
                if ((String.class).equals(field.getType())) {
                    // 根据字段类型决定结果集中使用哪种get方法从数据中取到数据
                    field.set(obj, "");
                }

                if (field.getType().equals(Integer.class)) {
                    field.set(obj, 0);
                }
                if (field.getType().equals(Date.class)) {
                    field.set(obj, "");
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
        return obj;
    }

    /**
     * 实体bean合并 将origin的值合并入destination，如果值为null，则不覆盖
     * @param origin
     * @param destination
     * @param <T>
     * @Auth marver
     */
    public static <T> void mergeObject(T origin, T destination) {
        if (origin == null || destination == null)
            return;
        if(!origin.getClass().equals(destination.getClass()))
            return;

        Field[] fields =origin.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            try {
                fields[i].setAccessible(true);
                Object value = fields[i].get(origin);
                if (null != value) {
                    fields[i].set(destination, value);
                }
                fields[i].setAccessible(false);
            }catch (Exception e) {
            }
        }
    }
}
